package com.jiangore.module;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Todo
 * @Author jiangtao
 * @CreateBy 2020-03-17 9:04 PM
 * @UpdateBy jiangtao
 * @Version v1.0
 */
@Slf4j
@RestController
public class RedisLockController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public String reduceStock() {
        String key = "goods_001";
        String clientId = UUID.randomUUID().toString();

        try {
            //key设置超时时间,10秒过期,防止程序突然崩溃导致死锁  redis.setnx(key, value , 5, 秒)
            boolean result = redisTemplate.opsForValue().setIfAbsent(key, clientId, 5, TimeUnit.SECONDS);
            if (!result) {
                return "error";
            }
            int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                int realStock = stock - 1;
                redisTemplate.opsForValue().set("stock", realStock + "");
                System.out.println("扣减成功,剩余库存:" + realStock + "");
            } else {
                System.out.println("扣减失败,库存不足");
            }
        } finally {
            if (clientId.equals(redisTemplate.opsForValue().get(key))) {
                //释放锁  防止程序异常出现死锁
                redisTemplate.delete(key);
            }
        }

        return "success";
    }
}
